import { openWindow } from '..';
import { dataURLtoBlob, urlToBase64 } from './base64Conver';
import { downloadByUrlApi } from '/@/api/sys/upload';
import { useMessage } from '/@/hooks/web/useMessage';
import { isObject } from '/@/utils/is';
import { CommonDownLoad } from '/@/api/admin/resoure';

const { createMessage } = useMessage();

/**
 * Download online pictures
 * @param url
 * @param filename
 * @param mime
 * @param bom
 */
export function downloadByOnlineUrl(url: string, filename: string, mime?: string, bom?: BlobPart) {
  urlToBase64(url).then((base64) => {
    downloadByBase64(base64, filename, mime, bom);
  });
}

/**
 * Download pictures based on base64
 * @param buf
 * @param filename
 * @param mime
 * @param bom
 */
export function downloadByBase64(buf: string, filename: string, mime?: string, bom?: BlobPart) {
  const base64Buf = dataURLtoBlob(buf);
  downloadByData(base64Buf, filename, mime, bom);
}

// 根据所需类型进行转码并返回下载地址
export function setEncoded(type: string, filename: string, data: string) {
  const encodedData: string = encodeURIComponent(data);
  return {
    filename: `${filename}.${type.toLowerCase()}`,
    href: `data:application/${
      type === 'svg' ? 'text/xml' : 'bpmn20-xml'
    };charset=UTF-8,${encodedData}`,
    data,
  };
}

/**
 * Download according to the background interface file stream
 * @param {*} data
 * @param {*} filename
 * @param {*} mime
 * @param {*} bom
 */
export function downloadByData(data: BlobPart, filename: string, mime?: string, bom?: BlobPart) {
  const blobData = typeof bom !== 'undefined' ? [bom, data] : [data];
  const blob = new Blob(blobData, { type: mime || 'application/octet-stream' });

  const blobURL = window.URL.createObjectURL(blob);
  const tempLink = document.createElement('a');
  tempLink.style.display = 'none';
  tempLink.href = blobURL;
  tempLink.setAttribute('download', filename);
  if (typeof tempLink.download === 'undefined') {
    tempLink.setAttribute('target', '_blank');
  }
  document.body.appendChild(tempLink);
  tempLink.click();
  document.body.removeChild(tempLink);
  window.URL.revokeObjectURL(blobURL);
}

/**
 * Download file according to file address
 * @param {*} sUrl
 */
export function downloadByUrl({
  url,
  target = '_blank',
  fileName,
}: {
  url: string;
  target?: TargetContext;
  fileName?: string;
}): boolean {
  const isChrome = window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  const isSafari = window.navigator.userAgent.toLowerCase().indexOf('safari') > -1;

  if (/(iP)/g.test(window.navigator.userAgent)) {
    console.error('Your browser does not support download!');
    return false;
  }
  if (isChrome || isSafari) {
    const link = document.createElement('a');
    link.href = url;
    link.target = target;

    if (link.download !== undefined) {
      link.download = fileName || url.substring(url.lastIndexOf('/') + 1, url.length);
    }

    if (document.createEvent) {
      const e = document.createEvent('MouseEvents');
      e.initEvent('click', true, true);
      link.dispatchEvent(e);
      return true;
    }
  }
  if (url.indexOf('?') === -1) {
    url += '?download';
  }

  openWindow(url, { target });
  return true;
}

export const exportData = (data: string, name = 'file', fileFormat = 'json') => {
  const fileName = `${name}.${fileFormat}`;
  let content = 'data:text/csv;charset=utf-8,';
  content += data;
  const encodedUri = encodeURI(content);
  const actions = document.createElement('a');
  actions.setAttribute('href', encodedUri);
  actions.setAttribute('download', fileName);
  actions.click();
};

export const downloadByApiUrl = async (
  url,
  { doc_ext = 'xlsx', fileName = `temp_${Date.now()}` } = {},
) => {
  // url 为后端接口地址
  let params = url;
  if (isObject(url)) {
    params = url.url;
  }

  const res = await downloadByUrlApi(params);

  const { data, headers, status } = res;

  if (status !== 200) {
    createMessage.error('系统错误');
    return;
  }

  const name = fileName.includes('.') ? fileName : `${fileName}.${doc_ext}`;
  const filename =
    headers['content-disposition'] && headers['content-disposition'].split('fileName=')[1];
  downloadByData(data, decodeURI(filename) || name);
};

export const commonDownFile = async (params: Object) => {
  const res = await CommonDownLoad(params);

  const { data, headers, status } = res;

  if (status !== 200) {
    createMessage.error('系统错误');
    return;
  }
  if (data.code) {
    createMessage.error(data.msg || '下载失败');
    return;
  }

  const filename =
    headers['content-disposition'] && headers['content-disposition'].split('fileName=')[1];
  console.log(decodeURI(filename));

  downloadByData(data, decodeURI(filename));
};
